package com.gitee.deeround.jdbchelper.resultSetExtractors;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

public class MapResultSetExtractor extends BaseResultSetExtractor implements ResultSetExtractor<List<Map<String, Object>>> {

    @Override
    public List<Map<String, Object>> extractData(ResultSet rs) throws SQLException, DataAccessException {
        List<Map<String, Object>> list = new ArrayList<>();
        ResultSetMetaData md = rs.getMetaData();
        int columnCount = md.getColumnCount();

        while (rs.next()) {
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();
            for (int j = 0; j < columnCount; j++) {
                String columnName = resolveColumnName(md.getColumnLabel(j + 1));
                Object value = getColumnValue(rs, j + 1, columnName, resolveDataType(md.getColumnType((j + 1))));
                if (value != null && LocalDateTime.class.isAssignableFrom(value.getClass())) {
                    Date date = Date.from(((LocalDateTime) value).atZone(ZoneId.systemDefault()).toInstant());
                    map.put(columnName, date);
                } else {
                    map.put(columnName, value);
                }
            }
            list.add(map);
        }

        return list;
    }
}
